<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑部门' : '新建部门'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入部门名称"
          maxlength="100"
          show-word-limit
          clearable
        />
      </el-form-item>

      <el-form-item label="父部门" prop="parent_id">
        <el-tree-select
          v-model="formData.parent_id"
          :data="departmentTreeOptions"
          :props="{ label: 'name', value: 'id', children: 'children' }"
          placeholder="选择父部门（留空为根部门）"
          clearable
          filterable
          check-strictly
          style="width: 100%"
          :render-after-expand="false"
          :loading="departmentLoading"
        />
      </el-form-item>

      <el-form-item label="部门负责人" prop="manager_id">
        <el-select
          v-model="formData.manager_id"
          placeholder="选择部门负责人（可选）"
          clearable
          filterable
          style="width: 100%"
          :loading="usersLoading"
        >
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="user.name || user.username"
            :value="user.id"
          >
            <div style="display: flex; align-items: center; gap: 8px;">
              <span>{{ user.name || user.username }}</span>
              <span style="color: #909399; font-size: 12px;">{{ user.email }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="排序" prop="order">
        <el-input-number
          v-model="formData.order"
          :min="0"
          :max="9999"
          style="width: 100%"
          placeholder="排序值，数字越小越靠前"
        />
      </el-form-item>

      <el-form-item label="部门描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="4"
          placeholder="请输入部门描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ isEdit ? '更新' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { getDepartmentTree, createDepartment, updateDepartment, type Department, type DepartmentCreate, type DepartmentUpdate } from '@/api/departments'
import { getUsers } from '@/api/users'
import type { User } from '@/types/user'

interface Props {
  visible: boolean
  department?: Department | null
  parentDepartment?: Department | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  department: null,
  parentDepartment: null
})

const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const submitting = ref(false)
const usersLoading = ref(false)
const departmentLoading = ref(false)
const userOptions = ref<User[]>([])
const departmentTreeOptions = ref<Department[]>([])

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.department)

const formData = ref<DepartmentCreate & { id?: string }>({
  name: '',
  parent_id: '',
  manager_id: '',
  order: 0,
  description: ''
})

const formRules: FormRules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 1, max: 100, message: '部门名称长度为1-100个字符', trigger: 'blur' }
  ],
  order: [
    { type: 'number', min: 0, max: 9999, message: '排序值必须在0-9999之间', trigger: 'blur' }
  ]
}

// 加载部门树选项（用于父部门选择，排除当前编辑的部门及其子部门）
const loadDepartmentTreeOptions = async () => {
  departmentLoading.value = true
  try {
    const response = await getDepartmentTree({ include_users: false })
    // 处理API响应格式：response.data 是 axios 响应，response.data.data 是实际的 API 响应数据
    const apiResponse = response?.data as any
    let tree: Department[] = []
    
    if (apiResponse && typeof apiResponse === 'object' && 'success' in apiResponse) {
      // API 响应格式：{ success: true, data: [...] }
      if (apiResponse.success && apiResponse.data) {
        tree = Array.isArray(apiResponse.data) ? apiResponse.data : []
      }
    } else if (Array.isArray(apiResponse)) {
      // 直接返回数组的情况
      tree = apiResponse
    } else if (Array.isArray(response?.data)) {
      // 兼容旧格式
      tree = response.data
    }
    
    // 如果是编辑模式，需要排除当前部门及其子部门
    if (isEdit.value && props.department) {
      tree = filterDepartmentTree(tree, props.department.id)
    }
    
    departmentTreeOptions.value = tree
    console.log('部门树选项加载成功:', tree, '数量:', tree.length)
  } catch (error) {
    console.error('加载部门树失败:', error)
    ElMessage.error('加载部门列表失败，请稍后重试')
    departmentTreeOptions.value = []
  } finally {
    departmentLoading.value = false
  }
}

// 过滤部门树，排除指定部门及其子部门
const filterDepartmentTree = (tree: Department[], excludeId: string): Department[] => {
  return tree
    .filter(dept => dept.id !== excludeId)
    .map(dept => {
      if (dept.children && dept.children.length > 0) {
        return {
          ...dept,
          children: filterDepartmentTree(dept.children, excludeId)
        }
      }
      return dept
    })
}

// 加载用户列表
const loadUsers = async () => {
  usersLoading.value = true
  try {
    const response = await getUsers({ limit: 200 })
    // 处理API响应格式
    const apiResponse = response?.data
    if (apiResponse?.success && apiResponse?.data) {
      const data = apiResponse.data
      userOptions.value = Array.isArray(data.items) ? data.items : (Array.isArray(data) ? data : [])
    } else if (Array.isArray(apiResponse?.data)) {
      userOptions.value = apiResponse.data
    } else {
      userOptions.value = []
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    userOptions.value = []
  } finally {
    usersLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    parent_id: props.parentDepartment?.id || '',
    manager_id: '',
    order: 0,
    description: ''
  }
  formRef.value?.clearValidate()
}

// 填充表单数据
const fillFormData = (department: Department) => {
  formData.value = {
    id: department.id,
    name: department.name,
    parent_id: department.parent_id || '',
    manager_id: department.manager_id || '',
    order: department.order || 0,
    description: department.description || ''
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    const submitData: DepartmentCreate | DepartmentUpdate = {
      name: formData.value.name,
      parent_id: formData.value.parent_id || undefined,
      manager_id: formData.value.manager_id || undefined,
      order: formData.value.order,
      description: formData.value.description || undefined
    }

    if (isEdit.value && props.department) {
      await updateDepartment(props.department.id, submitData)
      ElMessage.success('部门更新成功')
    } else {
      await createDepartment(submitData as DepartmentCreate)
      ElMessage.success('部门创建成功')
    }

    emit('success')
    dialogVisible.value = false
  } catch (error: any) {
    if (error !== false) {
      console.error('提交失败:', error)
      const errorMessage = error?.response?.data?.message || error?.message || (isEdit.value ? '部门更新失败' : '部门创建失败')
      ElMessage.error(errorMessage)
    }
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 监听对话框显示状态
watch(
  () => props.visible,
  async (visible) => {
    if (visible) {
      // 先加载部门树选项，确保数据可用
      await loadDepartmentTreeOptions()
      await loadUsers()
      if (props.department) {
        fillFormData(props.department)
      } else {
        resetForm()
      }
    } else {
      formRef.value?.resetFields()
    }
  },
  { immediate: false }
)
</script>

<style scoped>
:deep(.el-tree-select) {
  width: 100%;
}
</style>

